////AutoModify -By zxiaofan////
/*
 * 文件名：RestUtil.java
 * 版权：Copyright 2007-2016 517na Tech. Co. Ltd. All Rights Reserved.
 * 描述： RestUtil.java
 * 修改人：yunhai
 * 修改时间：2016年11月14日
 * 修改内容：新增
 */
package com.better517na.elasticseach.utils;


import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpHead;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

public class RestUtil {
    
    /**
     * http 请求.
     * @param url url.
     * @param param 参数.
     * @return 请求结果.
     */
    public static String post(String url, String param) {
        String result = null;
        try {
            CloseableHttpClient httpclient = HttpClients.createDefault();
            HttpPost httppost = new HttpPost(url);
            if (null != param) {
                StringEntity entity = new StringEntity(param, "utf-8");
                httppost.setEntity(entity);
            }
            httppost.setHeader("Content-Type", "application/json; charset=utf-8");
            HttpResponse response = httpclient.execute(httppost);
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode == 200) {
                result = EntityUtils.toString(response.getEntity(), "utf-8");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }


    /**
     * http 请求.
     * @param url url.
     * @return 请求结果.
     */
    public static Map<String,String> head(String url) {
        Map<String,String> result = new HashMap<String, String>();
        try {
            CloseableHttpClient httpclient = HttpClients.createDefault();
            HttpHead httpHead = new HttpHead(url);

            httpHead.setHeader("Content-Type", "application/json; charset=utf-8");
            HttpResponse response = httpclient.execute(httpHead);
            int statusCode = response.getStatusLine().getStatusCode();
            result.put("Status",String.valueOf(statusCode));
            if (statusCode == 200 && null !=response.getEntity()) {
                String rsp = EntityUtils.toString(response.getEntity(), "utf-8");
                result.put("Response",rsp);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }


    /**
     * post.
     *
     * @param url
     *            url
     * @param param
     *            param
     * @param logInteraction
     *            logInteraction
     * @param method
     *            method
     * @return String
     * @throws Exception
     *             Exception
     */
    public static String postForm(String url, String param, String method, String logInteraction) throws Exception {
        return postFrom(url, param, method, logInteraction);
    }




    /**
     * post 以表单形式,提交.
     * 添加方法注释.
     *
     * @param urlStr url 地址.
     * @param param param.
     * @param logMethod 日志方法.
     * @param logChannel 日志渠道.
     * @return 返回jieguo.
     * @throws Exception ex.
     */
    private static String postFrom(String urlStr, String param, String logMethod, String logChannel) throws Exception {
        String result = "";
        try {
            URL url = new URL(urlStr);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.addRequestProperty("content-type", "application/x-www-form-urlencoded;charset=utf-8");
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setRequestMethod("POST");
            connection.setUseCaches(false);
            connection.setInstanceFollowRedirects(true);
            connection.connect();
            DataOutputStream dataout = new DataOutputStream(connection.getOutputStream());
//            dataout.writeBytes(param);
            dataout.write(param.getBytes("UTF-8"));
            dataout.flush();
            dataout.close();
            InputStreamReader reader = new InputStreamReader(connection.getInputStream(), "UTF-8");
            BufferedReader bf = new BufferedReader(reader);
            String line;
            StringBuilder sb = new StringBuilder(); // 用来存储响应数据
            // 循环读取流,若不到结尾处
            while ((line = bf.readLine()) != null) {
                //sb.append(bf.readLine());
                sb.append(line).append(System.getProperty("line.separator"));
            }
            reader.close();
            bf.close();    // 重要且易忽略步骤 (关闭流,切记!)
            connection.disconnect(); // 销毁连接
            result = sb.toString();

        } catch (Exception e) {
           e.printStackTrace();
        }
        return result;
    }

    /**
     * get请求.
     *
     * @param url        请求地址
     * @param param      请求参数
     * @return String .
     * @throws IOException  ex.
     * @IOException exception ex.
     */
    public static String get(String url, String param) throws IOException {
        String result = "";
        BufferedReader in = null;
        InputStreamReader inputStream = null;
        try {
            url += "?" + param;
            URL realUrl = new URL(url);
            HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection();
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "keep-alive");
            conn.connect();
            inputStream = new InputStreamReader(conn.getInputStream(),"UTF-8");
            in = new BufferedReader(inputStream);
            String line;
            while (null != (line = in.readLine())) {
                result += line;
            }
            conn.disconnect();
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            if (null != in) {
                in.close();
            }
            if (null != inputStream){
                inputStream.close();
            }
        }
        return result;
    }



}

